package com.jochen.core.system.abs

import com.artemis.Aspect
import com.artemis.BaseEntitySystem
import com.artemis.utils.IntBag
import com.badlogic.gdx.Gdx

abstract class SortedIteratingSystem(aspect: Aspect.Builder): BaseEntitySystem(aspect){
    protected val sortedEntities = mutableListOf<Int>()
    
    private var needSort = true
    
    protected abstract fun sortEntities()
    
    private fun sort(){
        if(needSort){
            sortEntities()
            needSort = false
        }
    }
    
    override fun inserted(entityId: Int){
        sortedEntities.add(entityId)
        needSort = true
    }
    
    override fun removed(entityId: Int){
        if(sortedEntities.remove(entityId)){
            needSort = true
        }
    }
    
    override fun processSystem(){
        sort()
        sortedEntities.forEach(::process)
    }
    
    abstract fun process(entity: Int)
    
    override fun dispose(){
        sortedEntities.clear()
    }
}
